package com.fenghongzhang.day014;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;

public class Main2Activity extends AppCompatActivity {

    private Button startBind;
    private Button stopBind;

    private  Intent intent;
    private ServiceConnection serviceConnection;
    private MyService2.MyBinder myBinder;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        startBind = (Button) findViewById(R.id.start_bind);
        stopBind = (Button) findViewById(R.id.stop_bind);
       intent = new Intent(this, MyService2.class);
    }

    //启动
    public void start_bind(View view) {

        //匿名方式
         serviceConnection = new ServiceConnection() {
            //建立链接会调用
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                //IBinder - Mybinder.callshow()- >show
                 myBinder = (MyService2.MyBinder) service;
                //show()
                myBinder.callShow();
            }

            //端口链接调用.(非正常)
            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };
        bindService(intent,serviceConnection,BIND_AUTO_CREATE);
    }

    //停止
    public void stop_bind(View view) {
        unbindService(serviceConnection);
    }

    public void show2(View view) {
        myBinder.callShow2();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection);
    }

    public void start(View view) {
        startService(intent);
    }

    public void stop(View view) {
        stopService(intent);
    }
}
